package com.example.kafkademo.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import java.util.Properties;

public class SimpleProducer {

    public static void main(String[] args) {

        Properties props = new Properties();
        props.put("bootstrap.servers", "192.168.1.14:9092");  //kafka主机地址
        props.put("acks", "all");  //最慢最持久的提交消息
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);

        for (int i=0;i<100;i++) {
            producer.send(new ProducerRecord<String, String>("xiongjie-kafka", "good"+i, "morning"+i));
            System.out.println("消息发送成功"+i);
        }

        /**
         * 关键，生产者不是已经提交，才能将缓冲区数据写入硬盘。需要执行一下其中一个操作才行
         *  producer.flush();
         *  producer.close();
         *  或者睡眠一段时间
         *  注意：如果直接在main()中发送完就结束，那么消息是不会存储到硬盘上的，消费者也消费不到
         */
        producer.close();
    }

}
